const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const imgsUpload = (page, select_imgs, imgs_list, imgIds_list) => {
  let _this = page;
  let files = select_imgs.detail.file;
  let fileList = imgs_list;
  const fileList_tmp = imgs_list.length; // 记录当前文件列表的数量
  let imgIds = imgIds_list;
  let i = 0;
  files.forEach(item => {
    fileList.push({
      url: item.url,
      status: "uploading",
      message: "上传中",
    });
  });
  _this.setData({
    fileList: fileList
  });
  single_upload();

  function single_upload() {
    getApp().globalData.http.upload("name", files[i].url, {
      srcType: "1"
    }).then(res => {
      fileList[fileList_tmp + i].status = "success";
      imgIds.push(res.data.id);
      _this.setData({
        imgIds: imgIds,
        fileList: fileList
      });
      if (fileList.length > 0 && i < (files.length - 1 + fileList.length - 1)) {
        i++;
        single_upload();
      }
    }).catch(e => {
      // getApp().globalData.vant.toast(e.msg);
    });
  }
}

const previewImage = (imgs, current) => {
  wx.previewImage({
    urls: imgs,
    current: current,
    showmenu: true,
    success: (res) => {},
    fail: (res) => {},
    complete: (res) => {},
  });
}

const pay = (data, success, fail) => {
  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: `prepay_id=${data.prepayId}`,
    signType: data.signType,
    paySign: data.paySign,
    success(res) {
      getApp().globalData.http.levelNotify({
        orderNo: data.orderNo
      }).then(res => {
        getApp().globalData.vant.toast({
          type: "success",
          message: "支付成功",
          duration: 1000,
          onClose: () => {
            success && success();
          }
        });
      }).catch(e => {
        getApp().globalData.vant.toast.fail(!e.msg ? "支付失败" : e.msg);
      });
    },
    fail(res) {
      console.log("fail", res);
      fail && fail();
    }
  });
}

module.exports = {
  formatTime,
  imgsUpload,
  previewImage,
  pay,
}